<script setup lang="ts">
import { ref } from "vue";
import Taro, { useRouter } from "@tarojs/taro";
import { debounce } from "@tarojs/runtime";

import ApiOrder from "@/api/order";
import ApiPayment from "@/api/payment";
import ApiMerchant from "@/api/merchant";
import useFetch from "@/hooks/useFetch";
import ApiActivity from "@/api/activity";

import ByCell from "@/components/ui/ByCell.vue";
import Page from "@/components/common/Page.vue";
import ByEmpty from "@/components/ui/ByEmpty.vue";
import ByButton from "@/components/ui/ByButton.vue";
import ByAvatar from "@/components/ui/ByAvatar.vue";
import CouponList from "./components/CouponList.vue";
import CouponItem from "./components/CouponItem.vue";

import { PaymentCouponInfo } from "@/types/coupon";
import { GetApplyActivityListItem } from "@/types/activity";

import { TMerchantInfo } from "@/global";

const { params } = useRouter();
const q = params.q ? decodeURIComponent(params.q) : "";

// 获得活动商户的唯一key 「防止收款码被篡改」
const key = q?.split("=")[1];

// 根据Key获取活动详情
const { data: activityData } = useFetch<GetApplyActivityListItem>(
  ApiActivity.getApplyActivityDetailByKey,
  {
    defaultParams: { key },
    afterFetch: (res: any) => res?.detail,
  }
);

// 获取商户详情
const { data, loading: loadingInfo } = useFetch<TMerchantInfo>(
  ApiMerchant.getMerchantDetailByKey,
  {
    immediate: !!key,
    showLoading: true,
    defaultParams: { key },
    afterFetch: (res: any) => res?.merchant_detail,
    onSuccess() {
      Taro.setNavigationBarTitle({ title: "商户收款" });
    },
  },
  { hiddenToast: true }
);

// 输入金额
const amount = ref("");

/**
 * 处理金额输入
 * 1. 最多两位小数
 * 2. 最多存在一个小数点
 * 3. 整数部分不限制长度
 * 4. 初始值为空时，输入点号，自动补0.
 * @param 金额值
 */
const changeAmount = (value: string) => {
  if (value === "") return "";
  value = value.replace(/\./g, (_, offset, string) => {
    // 如果是第一个点，保留它
    if (offset === string.indexOf(".")) {
      return ".";
    }
    // 其他点都移除
    return "";
  });

  if (value === ".") return "0.";

  // 限制小数位数
  const parts = value.split(".");
  const length = parts[1]?.length || 0;

  return length === 0
    ? value
    : Number(value).toFixed(Math.min(length, 2)).toString();
};

// 防抖处理输入
const inputChange = debounce(() => {
  // 振动反馈
  Taro.vibrateShort({ type: "light" });
  amount.value = changeAmount(amount.value);
}, 300);

/**
 *  支付收款流程
 *  1. 创建订单
 *  2. 获取JSAPI支付参数
 *  3. 发起支付
 *  4. 反馈结果
 */
const loading = ref(false);
const createOrderAndPay = async () => {
  const {
    data: { value },
  } = await useFetch<{ sn: string }>(ApiOrder.createChargeOrder, {
    defaultParams: {
      key,
      pay_type: "wechat_pay",
      amount: parseFloat(amount.value),
      user_coupon_id: selectCoupon.value?.user_coupon_id || undefined,
    },
  });

  const {
    data: { value: payParams },
  } = await useFetch<any>(ApiPayment.payment, {
    defaultParams: {
      order_sn: value.sn,
      pay_type: "wechat_pay",
      // 订单类型 1 押金订单 2 收款订单 3 售票订单
      service_type: 2,
    },
  });

  console.log("payParams", payParams);

  Taro.requestPayment({
    timeStamp: payParams.time_stamp,
    nonceStr: payParams.nonce_str,
    package: payParams.package,
    signType: payParams.sign_type,
    paySign: payParams.pay_sign,

    // @ts-expect-error
    // payCompletedPageOptions: {
    //   templateId: "TIvXviQtM_C6zqbu91jMgw",
    //   templateData: {
    //     title: "支付成功",
    //     infos: [
    //       {
    //         key: "pay_amount",
    //         value: "￥1.2",
    //       },
    //       {
    //         key: "pay_time",
    //         value: "2025.10.20 17:30:20",
    //       },
    //     ],
    //   },
    // },
  }).then(
    (res) => {
      // @ts-expect-error
      if (res.payCompletedPage) {
        // @ts-expect-error
        res.payCompletedPage.onLoad(() => {
          console.log("支付订单详情页加载完成");
          console.log("处于支付订单详情页的时候【不允许】调用 wx.navigateTo");
        });

        // @ts-expect-error
        res.payCompletedPage.onUnload(() => {
          console.log("支付订单详情页卸载完成");
          console.log("退出支付订单详情页之后，允许调用 wx.navigateTo");

          // 重定向到首页
          Taro.reLaunch({ url: "/pages/index/index" });
        });
      } else {
        // 针对payCompletedPage的兼容补充

        // 两秒后跳转到支付结果页
        setTimeout(() => {
          Taro.redirectTo({
            url: "/packageMine/pages/charge/result?sn=" + payParams.sn,
          });
        }, 200);
      }
    },
    (err) => {
      console.error("支付失败", err);
      Taro.showToast({ icon: "error", title: "支付失败" });
    }
  );
};

const beforeCreateOrder = () => {
  const val = parseFloat(amount.value);

  if (val > 0) {
    loading.value = true;
    createOrderAndPay().finally(() => {
      loading.value = false;
    });
  } else {
    Taro.showToast({
      icon: "none",
      title: "请输入有效金额",
    });
  }
};

// 优惠券弹窗
const visible = ref(false);
function setVisible() {
  if (amount.value == "") {
    Taro.showToast({
      icon: "none",
      title: "请输入金额",
    });
    return;
  }

  visible.value = true;
}

// 选择的优惠券
const selectCoupon = ref<PaymentCouponInfo>();

function setSlectCoupon(coupon: PaymentCouponInfo) {
  selectCoupon.value = coupon;
  visible.value = false;
}
</script>

<template>
  <Page hiddenHeaderBg :bodyCenter="!data">
    <template #footer v-if="data">
      <view class="px-5.5 pt-3 pb-6">
        <view v-if="selectCoupon" class="text-center text-sm mb-1">
          预计优惠¥{{ selectCoupon?.discount_amount }}
        </view>

        <ByButton block size="large" :loading="loading" @tap="beforeCreateOrder"
          >支付
        </ByButton>
      </view>
    </template>

    <view v-if="data">
      <view class="flex justify-between items-center mx-5.5 my-6">
        <text class="text-2xl">付款给 {{ data?.merchant_title }}</text>
        <ByAvatar rounded :src="data?.merchant_logo_png" class="bg-[#f1f1f1]" />
      </view>

      <view class="mx-5.5">
        <view class="border-b-1 border-b-[#000]/20">
          <view class="text-lg text-#8D8D8F">消费总额</view>

          <view class="flex items-center">
            <text class="text-3xl">&yen;</text>
            <view class="ml-2 flex-auto">
              <input
                v-model="amount"
                type="digit"
                :focus="false"
                class="text-[100px] h-[1.6em]"
                @input="inputChange"
              />
            </view>
          </view>
        </view>

        <!-- <view class="mt-3">
          <template v-if="selectCoupon">
            <CouponItem :source="selectCoupon" />

            <view class="text-center mt-1">
              <text class="text-xs text-second" @tap="selectCoupon = undefined"
                >取消优惠</text
              >
            </view>
          </template>

          <ByCell v-else label="选择优惠券" next @tap="setVisible" />
        </view> -->
      </view>
    </view>

    <ByEmpty v-else-if="!loadingInfo" title="未获取到商户信息" />
  </Page>

  <page-container :show="visible" :round="true" @leave="visible = false">
    <CouponList
      v-if="visible"
      :merchant_id="data?.id"
      :amount="amount"
      :aid="activityData?.act_id"
      @close="visible = false"
      @selected="setSlectCoupon"
    />
  </page-container>
</template>
